﻿﻿using ConsoleApp2.Models;
using ConsoleApp2.Service;
using ConsoleApp2.Impl;
using System.Collections.Generic;
using System.Linq;
using ConsoleApp2.Enum;

namespace ConsoleApp2.Utils;

public class RoleManagerUtil
{
    private UserLoginService userLoginService { get; set; }
    private CodeService CodeService { get; set; }
    private UserRegisterService userRegisterService { get; set; }
    private LocalUserSystemService localUserSystemService { get; set; }
    private static int USER_INDEX_COUNT = 0;
    private static List<ConsoleApp2.Models.User> users = new List<ConsoleApp2.Models.User>();
    private PermissionService PermissionService { get; set; }
    private RoleService RoleService { get; set; }

    public RoleManagerUtil()
    {
        userLoginService = new UserLoginServiceImpl();
        CodeService = new CodeServiceImpl();
        localUserSystemService = new LocalUserSystemServiceImpl();
        userRegisterService = new UserRegisterServiceImpl();
        PermissionService = new PermissionServiceImpl();
        RoleService = new RoleServiceImpl();
    }

    public void LoginAfterRoleManger(ConsoleApp2.Models.User user)
    {
        Console.WriteLine($"欢迎{user.NickName}进入后台管理系统");
        Console.WriteLine("请选择你要做的事情");
        Console.WriteLine("按1----》查询所有用户信息");
        Console.WriteLine("按2----》给用户分配权限");
        Console.WriteLine("按3----》删除用户");
        Console.WriteLine("按4----》添加用户");
        Console.WriteLine("按5----》修改其他用户信息");
        Console.WriteLine("按6----》修改个人信息");
        Console.WriteLine("按7----》角色管理");
        Console.WriteLine("按8----》权限管理");
        Console.WriteLine("按q----》退出系统");
        
        string userInput = Console.ReadLine();
        while (true)
        {
            switch (userInput)
            {
                case "1":
                    if (HasPermission(user, PermissionName.QueryUser))
                    {
                        QueryAllUsers();
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "2":
                    if (HasPermission(user, PermissionName.AddPermission))
                    {
                        AssignPermissions(user);
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "3":
                    if (HasPermission(user, PermissionName.DeleteUser))
                    {
                        DeleteUser(user);
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "4":
                    if (HasPermission(user, PermissionName.AddUser))
                    {
                        AddUser();
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "5":
                    if (HasPermission(user, PermissionName.UpdateUser))
                    {
                        UpdateUser(user);
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "6":
                    UpdatePersonalInfo(user);
                    break;
                case "7":
                    if (HasPermission(user, PermissionName.QueryRole))
                    {
                        RoleManagement(user);
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "8":
                    if (HasPermission(user, PermissionName.QueryPermission))
                    {
                        PermissionManagement(user);
                    }
                    else
                    {
                        Console.WriteLine("你没有这个权限");
                    }
                    break;
                case "q":
                    Console.WriteLine("正在退出程序");
                    return;
                default:
                    Console.WriteLine("输入有误，请重新输入");
                    break;
            }
            Console.WriteLine("\n请选择你要做的事情：");
            userInput = Console.ReadLine();
        }
    }

    private void QueryAllUsers()
    {
        Console.WriteLine("正在查询用户");
        System.Threading.Thread.Sleep(1000);
        List<ConsoleApp2.Models.User> allUsers = localUserSystemService.GetAllUsers();
        foreach (var u in allUsers)
        {
            Console.WriteLine($"ID: {u.Id}");
            Console.WriteLine($"用户名: {u.UserName}");
            Console.WriteLine($"昵称: {u.NickName}");
            Console.WriteLine($"邮箱: {u.Email}");
            Console.WriteLine($"角色: {string.Join(", ", u.Roles.Select(r => r.RoleName))}");
            Console.WriteLine("----------------------------------------");
        }
    }

    private void AddUser()
    {
        Console.WriteLine("请输入新用户的用户名：");
        string userName = Console.ReadLine();
        Console.WriteLine("请输入新用户的密码：");
        string password = Console.ReadLine();
        Console.WriteLine("请输入新用户的昵称：");
        string nickName = Console.ReadLine();
        Console.WriteLine("请输入新用户的邮箱：");
        string email = Console.ReadLine();

        ConsoleApp2.Models.User newUser = new ConsoleApp2.Models.User()
        {
            UserName = userName,
            Password = Encory.EncryPwd(password),
            NickName = nickName,
            Email = email,
            CreateTime = DateTime.Now,
            UpdateTime = DateTime.Now,
            Roles = new List<Role>() { RoleService.GetAllRoles().First(r => r.RoleName == RoleName.普通用户) }
        };

        localUserSystemService.SaveUser(newUser);
        Console.WriteLine("用户添加成功");
    }

    private void UpdateUser(ConsoleApp2.Models.User admin)
    {
        Console.WriteLine("请输入要修改的用户ID：");
        if (int.TryParse(Console.ReadLine(), out int userId))
        {
            var userToUpdate = localUserSystemService.GetAllUsers().FirstOrDefault(u => u.Id == userId);
            if (userToUpdate != null)
            {
                Console.WriteLine("请输入新的昵称（直接回车保持原值）：");
                string newNickName = Console.ReadLine();
                if (!string.IsNullOrEmpty(newNickName))
                {
                    userToUpdate.NickName = newNickName;
                }

                Console.WriteLine("请输入新的邮箱（直接回车保持原值）：");
                string newEmail = Console.ReadLine();
                if (!string.IsNullOrEmpty(newEmail))
                {
                    userToUpdate.Email = newEmail;
                }

                userToUpdate.UpdateTime = DateTime.Now;
                Console.WriteLine("用户信息更新成功");
            }
            else
            {
                Console.WriteLine("用户不存在");
            }
        }
        else
        {
            Console.WriteLine("无效的用户ID");
        }
    }

    private void UpdatePersonalInfo(ConsoleApp2.Models.User user)
    {
        Console.WriteLine("请输入新的昵称（直接回车保持原值）：");
        string newNickName = Console.ReadLine();
        if (!string.IsNullOrEmpty(newNickName))
        {
            user.NickName = newNickName;
        }

        Console.WriteLine("请输入新的邮箱（直接回车保持原值）：");
        string newEmail = Console.ReadLine();
        if (!string.IsNullOrEmpty(newEmail))
        {
            user.Email = newEmail;
        }

        user.UpdateTime = DateTime.Now;
        Console.WriteLine("个人信息更新成功");
    }

    private void RoleManagement(ConsoleApp2.Models.User admin)
    {
        Console.WriteLine("角色管理");
        Console.WriteLine("1. 查看所有角色");
        Console.WriteLine("2. 创建新角色");
        Console.WriteLine("3. 修改角色权限");
        Console.WriteLine("4. 删除角色");
        Console.WriteLine("q. 返回上级菜单");

        string choice = Console.ReadLine();
        switch (choice)
        {
            case "1":
                List<Role> roles = RoleService.GetAllRoles();
                foreach (var role in roles)
                {
                    Console.WriteLine($"角色ID: {role.Id}");
                    Console.WriteLine($"角色名称: {role.RoleName}");
                    Console.WriteLine($"权限: {string.Join(", ", role.Permissions.Select(p => p.NickPermissionName))}");
                    Console.WriteLine("----------------------------------------");
                }
                break;
            case "2":
                if (HasPermission(admin, PermissionName.AddRole))
                {
                    CreateNewRole();
                }
                else
                {
                    Console.WriteLine("你没有创建角色的权限");
                }
                break;
            case "3":
                if (HasPermission(admin, PermissionName.UpdateRole))
                {
                    UpdateRolePermissions();
                }
                else
                {
                    Console.WriteLine("你没有修改角色权限的权限");
                }
                break;
            case "4":
                if (HasPermission(admin, PermissionName.DeleteRole))
                {
                    DeleteRole();
                }
                else
                {
                    Console.WriteLine("你没有删除角色的权限");
                }
                break;
            case "q":
                return;
            default:
                Console.WriteLine("无效的选择");
                break;
        }
    }

    private void PermissionManagement(ConsoleApp2.Models.User admin)
    {
        Console.WriteLine("权限管理");
        Console.WriteLine("1. 查看所有权限");
        Console.WriteLine("2. 创建新权限");
        Console.WriteLine("3. 修改权限信息");
        Console.WriteLine("4. 删除权限");
        Console.WriteLine("q. 返回上级菜单");

        string choice = Console.ReadLine();
        switch (choice)
        {
            case "1":
                List<Permission> permissions = PermissionService.GetAllPermissions();
                foreach (var permission in permissions)
                {
                    Console.WriteLine($"权限ID: {permission.Id}");
                    Console.WriteLine($"权限名称: {permission.NickPermissionName}");
                    Console.WriteLine($"权限代码: {permission.PermissionName}");
                    Console.WriteLine("----------------------------------------");
                }
                break;
            case "2":
                if (HasPermission(admin, PermissionName.AddPermission))
                {
                    CreateNewPermission();
                }
                else
                {
                    Console.WriteLine("你没有创建权限的权限");
                }
                break;
            case "3":
                if (HasPermission(admin, PermissionName.UpdatePermission))
                {
                    UpdatePermission();
                }
                else
                {
                    Console.WriteLine("你没有修改权限的权限");
                }
                break;
            case "4":
                if (HasPermission(admin, PermissionName.DeletePermission))
                {
                    DeletePermission();
                }
                else
                {
                    Console.WriteLine("你没有删除权限的权限");
                }
                break;
            case "q":
                return;
            default:
                Console.WriteLine("无效的选择");
                break;
        }
    }

    private void CreateNewRole()
    {
        Console.WriteLine("请输入新角色名称：");
        string roleName = Console.ReadLine();
        if (System.Enum.TryParse<RoleName>(roleName, out RoleName newRoleName))
        {
            Role newRole = new Role()
            {
                RoleName = newRoleName,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Permissions = new List<Permission>()
            };
            RoleService.GetAllRoles().Add(newRole);
            Console.WriteLine("角色创建成功");
        }
        else
        {
            Console.WriteLine("无效的角色名称");
        }
    }

    private void UpdateRolePermissions()
    {
        Console.WriteLine("请输入要修改的角色ID：");
        if (int.TryParse(Console.ReadLine(), out int roleId))
        {
            var role = RoleService.GetAllRoles().FirstOrDefault(r => r.Id == roleId);
            if (role != null)
            {
                Console.WriteLine("当前权限：");
                foreach (var permission in role.Permissions)
                {
                    Console.WriteLine($"- {permission.NickPermissionName}");
                }

                Console.WriteLine("\n可用权限：");
                var allPermissions = PermissionService.GetAllPermissions();
                foreach (var permission in allPermissions)
                {
                    Console.WriteLine($"- {permission.NickPermissionName}");
                }

                Console.WriteLine("\n请输入要添加的权限名称（多个权限用逗号分隔）：");
                string[] permissionNames = Console.ReadLine().Split(',');
                role.Permissions.Clear();
                foreach (var name in permissionNames)
                {
                    var permission = allPermissions.FirstOrDefault(p => p.NickPermissionName == name.Trim());
                    if (permission != null)
                    {
                        role.Permissions.Add(permission);
                    }
                }
                Console.WriteLine("角色权限更新成功");
            }
            else
            {
                Console.WriteLine("角色不存在");
            }
        }
        else
        {
            Console.WriteLine("无效的角色ID");
        }
    }

    private void DeleteRole()
    {
        Console.WriteLine("请输入要删除的角色ID：");
        if (int.TryParse(Console.ReadLine(), out int roleId))
        {
            var role = RoleService.GetAllRoles().FirstOrDefault(r => r.Id == roleId);
            if (role != null)
            {
                RoleService.GetAllRoles().Remove(role);
                Console.WriteLine("角色删除成功");
            }
            else
            {
                Console.WriteLine("角色不存在");
            }
        }
        else
        {
            Console.WriteLine("无效的角色ID");
        }
    }

    private void CreateNewPermission()
    {
        Console.WriteLine("请输入新权限名称：");
        string permissionName = Console.ReadLine();
        Console.WriteLine("请输入新权限显示名称：");
        string nickName = Console.ReadLine();

        if (System.Enum.TryParse<PermissionName>(permissionName, out PermissionName newPermissionName))
        {
            Permission newPermission = new Permission()
            {
                PermissionName = newPermissionName,
                NickPermissionName = nickName,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now
            };
            PermissionService.GetAllPermissions().Add(newPermission);
            Console.WriteLine("权限创建成功");
        }
        else
        {
            Console.WriteLine("无效的权限名称");
        }
    }

    private void UpdatePermission()
    {
        Console.WriteLine("请输入要修改的权限ID：");
        if (int.TryParse(Console.ReadLine(), out int permissionId))
        {
            var permission = PermissionService.GetAllPermissions().FirstOrDefault(p => p.Id == permissionId);
            if (permission != null)
            {
                Console.WriteLine("请输入新的显示名称：");
                string newNickName = Console.ReadLine();
                if (!string.IsNullOrEmpty(newNickName))
                {
                    permission.NickPermissionName = newNickName;
                    permission.UpdateTime = DateTime.Now;
                    Console.WriteLine("权限信息更新成功");
                }
            }
            else
            {
                Console.WriteLine("权限不存在");
            }
        }
        else
        {
            Console.WriteLine("无效的权限ID");
        }
    }

    private void DeletePermission()
    {
        Console.WriteLine("请输入要删除的权限ID：");
        if (int.TryParse(Console.ReadLine(), out int permissionId))
        {
            var permission = PermissionService.GetAllPermissions().FirstOrDefault(p => p.Id == permissionId);
            if (permission != null)
            {
                PermissionService.GetAllPermissions().Remove(permission);
                Console.WriteLine("权限删除成功");
            }
            else
            {
                Console.WriteLine("权限不存在");
            }
        }
        else
        {
            Console.WriteLine("无效的权限ID");
        }
    }

    private bool HasPermission(ConsoleApp2.Models.User user, PermissionName permissionName)
    {
        return PermissionService.UserHavePermission(user, permissionName);
    }

    private void AssignPermissions(ConsoleApp2.Models.User admin)
    {
        Console.WriteLine("请输入要分配权限的用户的用户名：");
        string targetUserName = Console.ReadLine();
        List<ConsoleApp2.Models.User> allUsers = localUserSystemService.GetAllUsers();
        ConsoleApp2.Models.User targetUser = allUsers.FirstOrDefault(u => u.UserName == targetUserName);
        if (targetUser == null)
        {
            Console.WriteLine("用户不存在");
            return;
        }

        Console.WriteLine("当前用户角色：");
        foreach (var role in targetUser.Roles)
        {
            Console.WriteLine($"- {role.RoleName}");
        }

        Console.WriteLine("\n可用角色：");
        var allRoles = RoleService.GetAllRoles();
        foreach (var role in allRoles)
        {
            Console.WriteLine($"- {role.RoleName}");
        }

        Console.WriteLine("\n请输入要分配的角色名称（多个角色用逗号分隔）：");
        string[] roleNames = Console.ReadLine().Split(',');
        targetUser.Roles.Clear();
        foreach (var name in roleNames)
        {
            var role = allRoles.FirstOrDefault(r => r.RoleName.ToString() == name.Trim());
            if (role != null)
            {
                targetUser.Roles.Add(role);
            }
        }
        Console.WriteLine("角色分配成功");
    }

    private void DeleteUser(ConsoleApp2.Models.User admin)
    {
        Console.WriteLine("请输入要删除的用户ID：");
        string userInputId = Console.ReadLine();
        int userId;
        if (int.TryParse(userInputId, out userId))
        {
            List<ConsoleApp2.Models.User> allUsers = localUserSystemService.GetAllUsers();
            ConsoleApp2.Models.User userToDelete = allUsers.FirstOrDefault(u => u.Id == userId);
            if (userToDelete != null)
            {
                if (localUserSystemService.DeleteUserById(userId))
                {
                    Console.WriteLine("正在删除用户");
                    Console.WriteLine("删除成功");
                }
                else
                {
                    Console.WriteLine("删除失败");
                }
            }
            else
            {
                Console.WriteLine("用户不存在");
            }
        }
        else
        {
            Console.WriteLine("无效的用户ID");
        }
    }
}